﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure.Dao;
using SqlSugar;
using SyntacticSugar;
using DormMS.IService;
using DormMS.Model;
using DormMS.Model.Enum;
using DormMS.Model.SearchModels;
using DormMS.Model.SearchModels.Activity;
using DormMS.Model.ViewModels;

namespace DormMS.Service
{
    /// <summary>
    /// 一分钱活动
    /// </summary>
    public class ActivityService : IActivityService
    {
        private SqlSugarClient db;

        #region 活动

        /// <summary>
        /// 分页获取活动列表
        /// </summary>
        /// <param name="search"></param>
        /// <param name="total"></param>
        /// <returns></returns>
        public IEnumerable<V_Activity> GetActivityList(ActivitySearchModel search, ref int total)
        {
            using (db = DbConfig.GetInstance())
            {
                db.CurrentFilterKey = "FalseDelte";
                search.OrderByFields = search.OrderByFields;

                var list = db.Queryable<Model.Activity>()
                    .Where(m => m.ActivityName.Contains(search.Keywords))
                    .OrderBy(search.OrderByFields).ToPageList(search.Skip / search.Take + 1, search.Take, ref total)
                    .Select(s => new V_Activity()
                    {
                        CoverImg = s.CoverImg,
                        LuckDrawID = s.LuckDrawID,
                        ContinuedTime = s.ContinuedTime,
                        IsDeleted = s.IsDeleted,
                        IsWinning = s.IsWinning,
                        ParticipateNum = s.ParticipateNum,
                        Id = s.Id,
                        ActivityName = s.ActivityName,
                        ActivityPrice = s.ActivityPrice,
                        ActivityStatus = s.ActivityStatus,
                        ActivityDetails = s.ActivityDetails,
                        PeopleNum = s.PeopleNum,
                        OpenTeamNum = s.OpenTeamNum,
                        StartTime = s.StartTime,
                        EndTime = s.EndTime,
                        AddUserId = s.AddUserId,
                        AddTime = s.AddTime,
                        EditUserId = s.EditUserId,
                        EditTime = s.EditTime,
                        TeamCount = db.Queryable<Model.ActivityTeam>().Where(t => t.ActivityId == s.Id).Count()
                    }).ToList();
                return list;
            }
        }

        /// <summary>
        /// 获取活动信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public Model.Activity GetActivityInfo(int Id)
        {
            using (db = DbConfig.GetInstance())
            {
                var model = db.Queryable<Model.Activity>().SingleOrDefault(t => t.Id == Id);
                return model;
            }
        }

        /// <summary>
        /// 验证活动名称是否存在
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="activityName"></param>
        /// <returns></returns>
        public bool CheckActivityName(int Id, string activityName)
        {
            bool success = false;
            using (db = DbConfig.GetInstance())
            {
                var list = db.Queryable<Model.Activity>().Where(t => t.Id != Id && t.ActivityName == activityName);
                if (list.Count() == 0)
                {
                    success = true;
                }
                return success;
            }
        }

        /// <summary>
        /// 获取活动信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public V_Activity GetVActivityInfo(int Id)
        {
            V_Activity vActivity = null;
            using (db = DbConfig.GetInstance())
            {
                string sql =
                    $@"select t1.*,(select count(1) from ActivityTeam g where g.ActivityId=t1.Id) TeamCount from Activity t1 where t1.Id={
                        Id}";
                var dt = db.GetDataTable(sql);
                if (dt.Rows.Count > 0)
                {
                    vActivity = dt.TryToList<V_Activity>()[0];
                }
                return vActivity;
            }
        }

        /// <summary>
        /// 修改活动
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool EditActivity(Model.Activity model)
        {
            using (db = DbConfig.GetInstance())
            {
                return db.Update<Model.Activity>(model);
            }
        }

        /// <summary>
        /// 增加活动
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int AddActivity(Model.Activity model)
        {
            using (db = DbConfig.GetInstance())
            {
                return db.Insert<Model.Activity>(model).ObjToInt();
            }
        }

        /// <summary>
        /// 删除活动
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool DelActivity(int Id)
        {
            using (db = DbConfig.GetInstance())
            {
                return db.Update<Model.Activity>(new { IsDeleted = true }, m => m.Id == Id);
            }
        }

        /// <summary>
        /// 更新活动状态
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public bool UpdateActivityStatus(int Id, int status)
        {
            using (db = DbConfig.GetInstance())
            {
                return db.Update<Model.Activity>(new { ActivityStatus = status }, m => m.Id == Id);
            }
        }
        #endregion


        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        public V_Activity GetActivityTop1()
        {
            V_Activity v_activity = null;
            using (db = DbConfig.GetInstance())
            {
                string sql =
                    $@"select top 1 * from Activity  where StartTime<'" + DateTime.Now + "' and EndTime>'" + DateTime.Now + "' and IsDeleted=0 and ActivityStatus=0 order by Id desc";
                var dt = db.GetDataTable(sql);
                if (dt.Rows.Count > 0)
                {
                    v_activity = dt.TryToList<V_Activity>()[0];
                }
                return v_activity;
            }

        }
        /// <summary>
        /// 获取所有在时间内的一分钱活动
        /// </summary>
        /// <returns></returns>
        public List<V_Activity> GetActivityListAll()
        {
            using (db = DbConfig.GetInstance())
            {
                db.CurrentFilterKey = "";
                string sql =
                    $@"select * from Activity  where StartTime<'" + DateTime.Now + "' and EndTime>'" + DateTime.Now + "' and IsDeleted=0 and ActivityStatus=0";
                var list = db.SqlQuery<V_Activity>(sql).OrderBy("Id", OrderByType.Desc).ToList();
                return list;
            }
        }

        public bool IsCanCreat(int memberId, int actId)
        {
            using (db = DbConfig.GetInstance())
            {
                var act = db.Queryable<Activity>().SingleOrDefault(t => t.Id == actId);

                if (act == null || act.EndTime.Date < DateTime.Today || act.ActivityStatus == 1 || act.StartTime.Date > DateTime.Today)
                {
                    throw new Exception("活动还未开始或已下架");
                }

                int ncount = db.Queryable<Model.ActivityTeam>().Where(t => t.UserId == memberId && t.TeamStatus == 0 && t.EndTime >= DateTime.Now).Count();
                if (ncount > 0)
                {
                    throw new Exception("您已在开团中");
                }

                if (act.OpenTeamNum > 0)
                {
                    int hcount = db.Queryable<Model.ActivityTeam>().Where(t => t.UserId == memberId&&t.ActivityId==act.Id).Count();
                    if (hcount >= act.OpenTeamNum)
                    {
                        throw new Exception("您的开团次数已达上限");
                    }
                }

                return true;
            }
        }


        public bool IsCanJoin(int memberId, int actId,int groupId)
        {
            using (db = DbConfig.GetInstance())
            {
                var act = db.Queryable<Activity>().SingleOrDefault(t => t.Id == actId);

                if (act == null || act.EndTime.Date < DateTime.Today || act.ActivityStatus == 1 || act.StartTime.Date > DateTime.Today)
                {
                    throw new Exception("活动还未开始或已下架");
                }

                var group = db.Queryable<Model.ActivityTeam>().SingleOrDefault(t => t.Id == groupId);
                
                if (group==null ||group.EndTime<DateTime.Now)
                {
                    throw new Exception("团已经结束");
                }
                var mcount = db.Queryable<Model.ActivityTeamMembers>().Where(t => t.ActivityTeamId == groupId).Count();
                if (mcount >=act.PeopleNum)
                {
                    throw new Exception("您来晚了，团已满员");
                }
                //if (act.ParticipateNum > 0)
                //{
                    int hcount = db.Queryable<Model.ActivityTeamMembers>().Where(t => t.UserId == memberId).Count();
                    if (hcount >= 1)
                    {
                        throw new Exception("您已是老会员，新会员才能参团，赶快去开团吧");
                    }
                //}

                return true;
            }
        }
    }
}
